package com.ocean.core.log;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * 调试开发全局控制台日志打印输出
 *
 * @author zhang
 * @since 2021/9/6
 */
@Order(101)
@Aspect
@Component
public class WebLogAspect {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("execution(public * com.ocean.*.controller..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request;
        if (attributes != null) {
            //记录下请求内容
            request = attributes.getRequest();
            logger.info("URL : " + request.getRequestURL().toString());
            logger.info("请求方式 : " + request.getMethod());
            logger.info("IP : " + request.getRemoteAddr());
            logger.info("类方法 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            logger.info("请求参数 : " + Arrays.toString(joinPoint.getArgs()));
            Enumeration<String> enu = request.getParameterNames();
            while (enu.hasMoreElements()) {
                String name = enu.nextElement();
                logger.info("更多参数 : " + "name:{},value:{}", name, request.getParameter(name));
            }
        }
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) {
        if (ret != null && ret.toString().length() > 300) {
            ret = ret.toString().substring(0, 300) + "...";
        }
        logger.info("返回参数 : " + ret);
    }
}
